﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using MMM.Core.Domain;
using ServiceStack.ServiceHost;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using MMM.Services.Base;
using MMM.Services.Operations;
using MMM.Services.Type;
using MMM.Core;
using MMM.Services.Response;
using ServiceStack.OrmLite;
using ServiceStack.ServiceInterface;


namespace MMM.Services
{

    public class PermissionTreeService : RestServiceBase<PermissionTree>
    {

        IRepository<Module> moduleRep = ApplicationContext.Container.GetInstance<IRepository<Module>>();
        IRepository<Function> funRep = ApplicationContext.Container.GetInstance<IRepository<Function>>();

        public override object OnGet(PermissionTree request)
        {
            string userName = request.userName;
            string rootName = request.menuClass;
            var node= this.GetCacheClient().Get<PermissionTree>(rootName);
            if (node==null)
            {
                node = new PermissionTree() { id = Guid.Empty };
                var module = moduleRep.GetAll(t => t.Name == rootName).First();
                addMod(node, module.Id, userName);
                this.GetCacheClient().Add<PermissionTree>(rootName, node);
            }
            // addNode(node, request.RoleID);
            return node;
        }
        /// <summary>
        /// 添加模块
        /// </summary>
        /// <param name="rootNode"></param>
        /// <param name="parentID"></param>
        /// <param name="name"></param>
        private void addMod(PermissionTree rootNode, Guid? parentID, string name)
        {
            
            var moduleList = moduleRep.GetAll(t => t.ParentID == parentID.Value).OrderBy(t => t.OrderIndex);
            if (moduleList.Count() > 0)
            {
                foreach (var item in moduleList)
                {
                    var node = new PermissionTree { iconCls = item.Image, expanded = true, id = item.Id, leaf = false, level = item.MLevel, text = item.Name };
                    if (string.IsNullOrEmpty(item.Image))
                    {
                        node.iconCls = "icon-module";
                    }
                    rootNode.children.Add(node);
                    addMod(node, item.Id, name);
                }
            }

            addFun(rootNode, parentID, name);
        }
        /// <summary>
        /// 添加功能
        /// </summary>
        /// <param name="rootNode"></param>
        /// <param name="moduleID"></param>
        /// <param name="name"></param>
        private void addFun(PermissionTree rootNode, Guid? moduleID, string name)
        {
            IRepository<User> userRep = ApplicationContext.Container.GetInstance<IRepository<User>>();
            IRepository<RoleUser> roleUserRep = ApplicationContext.Container.GetInstance<IRepository<RoleUser>>();
            IRepository<UserPermission> userPerRep = ApplicationContext.Container.GetInstance<IRepository<UserPermission>>();
            IDictionary<Guid?, int> dic = new Dictionary<Guid?, int>();

            //获取用户信息
            var userList = userRep.GetAll(t => t.Name == name);

            Guid? userID = userList.First().Id;

            //获取对应的角色，并且使用缓存机制保存起来
            //var roleList = roleUserRep.GetAll(t => t.UserID == userID.Value);
            var roleList = this.GetCacheClient().Get<List<RoleUser>>("roleList");
            if (roleList == null)
            {
                roleList = roleUserRep.GetAll().ToList();
                this.GetCacheClient().Add<List<RoleUser>>("roleList", roleList);
            }
            foreach (var item in roleList)
            {
                if (item.UserID == userID)
                {
                    //获取所具有哪些的权限功能，并用缓存机制保存起来
                    //IEnumerable<UserPermission> userPerList = userPerRep.GetAll(t => t.RoleID == item.RoleID.Value && t.Type == 1 && t.Value != 0);
                    var userPerList = this.GetCacheClient().Get<List<UserPermission>>("userPerList");
                    if (userPerList == null)
                    {
                        userPerList = userPerRep.GetAll().ToList();
                        this.GetCacheClient().Add<List<UserPermission>>("userPerList", userPerList);
                    }
                    foreach (var func in userPerList)
                    {
                        if (func.RoleID == item.RoleID.Value && func.Type == 1 && func.Value != 0)
                        {
                            if (dic.ContainsKey(func.FID))
                            {
                                dic[func.FID] = func.Value | dic[func.FID];
                            }
                            else
                            {
                                dic.Add(func.FID, func.Value);
                            }
                        }
                    }
                }
            }

            //获取功能模块，并用缓存机制的方式保存起来
            //var funList = funRep.GetAll(t => t.ModuleID == moduleID.Value && t.Value != 0).OrderBy(t => t.OrderIndex);
            var funList = this.GetCacheClient().Get<List<Function>>("funList");
            if (funList == null)
            {
                funList = funRep.GetAll().OrderBy(t => t.OrderIndex).ToList();
                this.GetCacheClient().Add<List<Function>>("funList", funList);
            }
            if (funList.Count() > 0)
            {
                //rootNode.isVisible = true;
                foreach (var item in funList)
                {
                    if (item.ModuleID == moduleID.Value && item.Value != 0)
                    {
                        if (dic.ContainsKey(item.Id))
                        {
                            var node = new PermissionTree { iconCls = item.Image, id = item.Id, leaf = true, text = item.Name, url = item.Url };
                            if (item.Image == "" || item.Image == null)
                            {
                                node.iconCls = "icon-grid";
                            }
                            node.Value = dic[item.Id];
                            rootNode.children.Add(node);
                            //node.isVisible = true;
                        }
                    }
                }
            }
        }
    }

    [Serializable]
    [Route("/api/permissiontree", "GET")]
    public class PermissionTree : JsonNode<PermissionTree>
    {
        public PermissionTree()
        {
            Value = 0;
        }
        public string userName { get; set; }
        public int Value { get; set; }
        public string menuClass { get; set; }
        public string url { get; set; }
    }
}
